import React, { useState, useEffect, useRef } from 'react';
import {
  Breadcrumb,
  Button,
  Card,
  Form,
  Radio,
  DatePicker,
  Table,
  Tag,
  Space,
  message,
  Modal,
} from 'antd';
import { EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { Link } from 'react-router-dom';

// import { channelAPI } from 'api/channel';
import { delArticlesAPI, getArticlesAPI } from 'api/articles';
import defaultImg from 'assets/error.png';
import Channel from 'components/Channel';

const { RangePicker } = DatePicker;

export default function ArticleList(_props) {
  //11.1存筛选后的 条件数据  不然按分页的时候会重新发没有条件的请求
  const formDateRef = useRef();
  //13.1 保存点击页数时的  page和 per_page
  const pageRef = useRef({});

  // 12.1 点击删除按钮 删除文章
  const handleDelArticles = (id) => {
    // 15.1 二次确认 模态框
    Modal.confirm({
      title: '温馨提示',
      content: (
        <div>
          <p>你真的要删除吗?</p>
        </div>
      ),
      onOk: async () => {
        await delArticlesAPI(id);
        message.success('删除成功', 1);
        // console.log(31, articlesList);
        //13.4假如 删除最后一页 的最后一个刷新 到前一页  并且 第一页时 没有数据 不会跳转到第0页
        if (articlesList.results.length === 1 && pageRef.current.page > 1) {
          pageRef.current.page--;
        }
        //刷新页面
        //13.3 使用保存的页数  有一个bug 点击其他页面删除 再筛选 再删除会跳转到 刚刚保存的页数  解决:13.4 筛选后清空page
        // const page = pageRef.current || {};
        // console.log(333, page);
        const formDate = formDateRef.current || {};
        articlesFn({ ...pageRef.current, ...formDate });
      },
    });
  };

  //10.1标签数组 写出来  不然很乱
  const articleStatus = [
    { id: -1, name: '全部', color: 'magenta' },
    { id: 0, name: '草稿', color: 'orange' },
    { id: 1, name: '待审核', color: 'red' },
    { id: 2, name: '审核通过', color: 'green' },
    { id: 3, name: '审核失败', color: 'cyan' },
  ];

  //1,声明频道列表channelList  //移出全局组件
  // const [channelList, setChannelList] = useState([]);
  // const channelFn = async () => {
  //   const res = await channelAPI();
  //   // console.log(25, res);
  //   setChannelList(res.data.channels);
  // };

  //声明 获取文章列表 渲染表格数据
  const [articlesList, setArticlesList] = useState([]);
  const articlesFn = async (params) => {
    const res = await getArticlesAPI(params);
    // console.log(33, res);
    setArticlesList(res.data);
  };

  //2,钩子请求 数据
  useEffect(() => {
    // channelFn()移出全局组件;
    articlesFn();
  }, []);

  //分页发送请求 传参
  const handlePageChange = (page, per_page) => {
    // 13.2 保存点击时的页数
    pageRef.current = { page, per_page };
    // console.log('page', page, per_page);
    // 11.3,使用formDateRef存的数据
    const formDate = formDateRef.current || {};
    articlesFn({ page, per_page, ...formDate });
  };
  //提交表单
  const onFinish = (values) => {
    // console.log('values', values);
    let formDate = {
      ...values,
    };

    // 1, 文章状态不传为全部; delete是es6 删除对象键名的方法
    if (formDate.status === -1) {
      delete formDate.status;
      // console.log('formDate', formDate);
    }

    //2,频道id 不传为全部
    if (formDate.date) {
      //获取日期 然后转格式 赋值
      const begin_pubdate = formDate.date[0]
        .startOf('day')
        .format('YYYY-MM-DD HH:mm:ss');
      const end_pubdate = formDate.date[1]
        .endOf('day')
        .format('YYYY-MM-DD HH:mm:ss');
      //点语法存入对象中
      formDate.begin_pubdate = begin_pubdate;
      formDate.end_pubdate = end_pubdate;
      //删除原来日期组件
      delete formDate.date;
    }
    //完成
    // console.log('formDate', formDate); //
    //转换为JSON  目的 是为了 去除值为undefined的键
    formDate = JSON.parse(JSON.stringify(formDate));
    // console.log('formDate', formDate);
    articlesFn(formDate);
    // 11.2保存数据
    formDateRef.current = formDate;
    //13.4 筛选后清空page 清空pageRef数据
    pageRef.current = {};
  };

  //表格相关数据
  const columns = [
    {
      title: '封面',
      dataIndex: 'cover',

      render: (value) => {
        // console.log(value);
        return value.images.length ? (
          <img src={value.images[0]} alt="" width="100" height="60" />
        ) : (
          <img src={defaultImg} alt="" width="100" height="60" />
        );
      },
    },
    {
      title: '标题',
      dataIndex: 'title',
    },
    {
      title: '状态',
      dataIndex: 'status',
      //10.2 自定义渲染
      render: (value) => {
        const currentItem = articleStatus.find((item) => item.id === value);
        return <Tag color={currentItem.color}> {currentItem.name}</Tag>;
      },
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate',
    },
    {
      title: '阅读数',
      dataIndex: 'read_count',
    },
    {
      title: '评论数',
      dataIndex: 'comment_count',
    },
    {
      title: '点赞数',
      dataIndex: 'like_count',
    },
    {
      title: '操作',
      key: 'action',
      render: (value, record) => {
        return (
          <Space>
            <Button
              type="primary"
              shape="circle"
              icon={<EditOutlined />}
              // 20.2 跳转 到编制  并且 传id
              onClick={() => _props.history.push(`/edit/${record.id}`)}
            />

            <Button
              type="dashed"
              shape="circle"
              danger
              onClick={() => handleDelArticles(record.id)}
              icon={<DeleteOutlined style={{ color: 'red' }} />}
            />
          </Space>
        );
      },
    },
  ];

  return (
    <div style={{ height: 'calc (100vh-64px)', overflow: 'auto', padding: 24 }}>
      <Card
        title={
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>内容管理</Breadcrumb.Item>
          </Breadcrumb>
        }
        bordered={false}
        // style={{ width: 300 }}
      >
        <Form
          onFinish={onFinish}
          autoComplete="off"
          initialValues={{ status: -1 }}
        >
          <Form.Item label="状态" name="status">
            <Radio.Group>
              <Radio value={-1}>全部</Radio>
              <Radio value={0}>草稿</Radio>
              <Radio value={1}>待审核</Radio>
              <Radio value={2}>审核通过</Radio>
              <Radio value={3}>审核失败</Radio>
            </Radio.Group>
          </Form.Item>

          <Form.Item label="频道" name="channel_id">
            <Channel></Channel>
          </Form.Item>

          <Form.Item label="日期" name="date">
            <RangePicker></RangePicker>
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              筛选
            </Button>
          </Form.Item>
        </Form>

        <p>根据筛选条件共查询到 {articlesList.total_count} 条结果：</p>
        <Table
          columns={columns}
          dataSource={articlesList.results}
          rowKey="id"
          pagination={{
            onChange: handlePageChange,
            position: ['bottomCenter'],
            pageSize: articlesList.per_page,
            total: articlesList.total_count,
            current: articlesList.page,
          }}
        />
      </Card>
    </div>
  );
}
